package order;

import enums.*;
import goods.Goods;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.Logger;
import play.db.jpa.Model;
import play.modules.paginate.JPAExtPaginator;
import product.merchant.ProductSpecMerchant;
import util.common.ConvertUtil;
import util.common.DateUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

//import org.hibernate.impl.QueryImpl;


/**
 * 订单条目.
 */
@Entity
@Table(name = "order_items")
public class OrderItem extends Model {

    public static final String CACHE_BY_ORDER_ID = "CACHE_BY_ORDER_ID_";

    /**
     * 商品信息
     */
    @JoinColumn(name = "goods_id", nullable = true)
    @ManyToOne
    public Goods goods;

    /**
     * 订单信息
     */
    @JoinColumn(name = "order_id", nullable = true)
    @ManyToOne
    public Order order;

    /**
     * 购买数量
     */
    @Column(name = "buy_number")
    public Integer buyNumber;

    /**
     * 销售单价
     */
    @Column(name = "sale_price")
    public Double salePrice;

    /**
     * 总金额 = 销售单价*购买数量
     */
    @Column(name = "amount")
    public Double amount;

    /**
     * 成本价
     */
    @Column(name = "original_price")
    public Double originalPrice;

    /**
     * 合伙人价格
     */
    @Column(name = "partner_price")
    public Double partnerPrice;

    /**
     * 类型
     */
    @Column(name = "type")
    @Enumerated(EnumType.STRING)
    public OrderItemType type;


    /**
     * 状态
     */
    @Column(name = "status")
    @Enumerated(EnumType.ORDINAL)
    public GoodsStatus status;   //FIXME: OrderStatus or OrderItemStatus

    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 订单创建时间
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 更新时间
     */
    @Column(name = "updated_at")
    public Date updatedAt;

    @Transient
    public String url;

    public String originalName = "";

    public String imagePath = "";

    /**
     * 是否已投诉
     */
    @Column(name = "trial_status")
    @Enumerated(EnumType.ORDINAL)
    public TrialStatus trialStatus;


    /**
     * 是否取消订单
     */
    @Column(name = "cancel_status")
    @Enumerated(EnumType.ORDINAL)
    public CancelStatus cancelStatus;


    /**
     * 取消订单类型
     */
    @Column(name = "cancel_type")
    @Enumerated(EnumType.STRING)
    public CancelType cancelType;


    /**
     * 取消订单用户
     */
    @Column(name = "cancel_user_id")
    public Long cancelUserId;




    @Column(name = "cancel_reason")
    public String cancelReason;





    // 申诉状态
    @Transient
    public String trialStr;



    @Transient
    public String pt1Name;

    @Transient
    public String pName;

    @Transient
    public String unit;

    @Transient
    public String spec;

    @Transient
    public String sumBuyNumber;

    @Transient
    public String sumAmount;

    @Transient
    public Integer sumCount;


    public OrderItem() {
        super();
    }

    public OrderItem(Order order, ProductSpecMerchant product, Integer buyNumber) {
        this.goods = product.findGoods(order.webUser);
        this.order = order;
        this.buyNumber = buyNumber;
        //TODO 到时候 重新规划价格
//        this.facePrice = product.originalPrice;
//        this.originalPrice = product.originalPrice;
//        this.salePrice = product.salePrice;
        this.deleted = DeletedStatus.UN_DELETED;
        this.status = GoodsStatus.OPEN;
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    public OrderItem(Order order, ProductSpecMerchant product, Integer buyNumber, OrderItemType type) {
        this.goods = product.findGoods(order.webUser);
        this.order = order;
        this.buyNumber = buyNumber;
        //TODO 到时候重新规划价格
//        this.facePrice = product.originalPrice;
//        this.originalPrice = product.originalPrice;
//        this.salePrice = product.salePrice;
        this.deleted = DeletedStatus.UN_DELETED;
        this.status = GoodsStatus.OPEN;
        this.type = type;
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }


    public OrderItem(Order order, ProductSpecMerchant product, Double amount , Integer buyNumber, OrderItemType type) {
        this.goods = product.findGoods(order.webUser);
        this.order = order;
        this.buyNumber = buyNumber;
//        this.facePrice = product.originalPrice;
        this.amount = amount * buyNumber;
        this.originalPrice = product.merchantPrice;
        this.salePrice = amount;
        this.deleted = DeletedStatus.UN_DELETED;
        this.status = GoodsStatus.OPEN;
        this.type = type;
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }



    /**
     * 更新对象.
     */
    public static OrderItem update(Long id, OrderItem newObject) {
        OrderItem item = OrderItem.findById(id);
        if (item == null) {
            return null;
        }
        item.save();
        return item;
    }

    public static Boolean delete(Long id) {

        OrderItem item = OrderItem.findById(id);
        if (item == null) {
            return Boolean.FALSE;
        }
        item.deleted = DeletedStatus.DELETED;
        item.save();
        return Boolean.TRUE;
    }


    public static List<OrderItem> getListByOrder(Order order) {
        return OrderItem.find("order.id = ?1 and deleted = ?2", order.id, DeletedStatus.UN_DELETED).fetch();
    }

//    public static List<Map<String, Object>> findListByOrderWithSQL(Order order) {
//        StringBuilder sb = new StringBuilder(" select o.buyNumber as buyNumber,round(o.salePrice , 2) as salePrice,o.createdAt as createdAt,o.deleted as deleted,o.status as status,o.type as type,o.amount as amount,o.goods as goods from  OrderItem o where o.order.id = " + order.id + " and o.deleted = 0 order by createdAt desc ");
//        String hql = sb.toString();
//        Query query = JPA.em().createQuery(hql);
//        query.unwrap(QueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//        List<Map<String, Object>> resultlist = query.getResultList();
//        return resultlist;
//    }

    public static OrderItem getByOrder(Order order) {
        return OrderItem.find("order.id = ?1 and deleted = ?2", order.id, DeletedStatus.UN_DELETED).first();
    }

    /**
     * 判断 OrderItem 的购买数量
     *
     * @param id
     * @return
     */
    public static Long countByGoodsAndPayOrder(Long id, WebUser user) {
        return OrderItem.count("goods.serialId = ?1 and order.payedAt != null and order.webUser = ?2", id , user);
    }

    /**
     * 判断 OrderItem 的今日购买次数
     *找出某人今天购买某个产品的次数
     * @param id
     * @return
     */
    public static  Long countByGoodsAndPayOredreTodayCount(long id ,WebUser user){
        return  OrderItem.count("goods.serialId=?1 and order.payedAt !=null and order.webUser=?2 and order.createdAt between ?3 and ?4",id,user,DateUtil.getBeginOfDay(new Date()),DateUtil.getEndOfDay(new Date()));

    }

    public static Long getOrderItemCount(Order order) {
        return OrderItem.count("order.id = ?1 and deleted = ?2 ", order.id, DeletedStatus.UN_DELETED);
    }

    public static ProductSpecMerchant getProductSpecMerchantByOrderItem(OrderItem orderItem) {
        return ProductSpecMerchant.findById(orderItem.goods.serialId);
    }

    /**
     * 根据订单号 查询 OrderItems
     * 因为订单生成后, 不能进行对 orderItems 进行变动
     * 所以,此方法可以尽量避免查询数据库
     *
     * @param order
     * @return
     */
    public static List<OrderItem> findByOrder(final Order order) {
        return OrderItem.find("order = ?1 and deleted = ?2", order, DeletedStatus.UN_DELETED).fetch();
//        return CacheHelper.getCache(CACHE_BY_ORDER_ID + order.id, new CacheCallBack<List<OrderItem>>() {
//            @Override
//            public List<OrderItem> loadData() {
//                return OrderItem.find("order = ? and deleted = ?", order, DeletedStatus.UN_DELETED).fetch();
//            }
//        });
    }
    public static ProductSpecMerchant getProductByOrderItem(OrderItem orderItem){
//        Long productId = Long.valueOf(orderItem.goods.serial.replace("PRODUCT_", "").trim());
        return ProductSpecMerchant.findById(orderItem.goods.serialId);
    }


    public static Long countByGoods(Long goodsId) {
        return OrderItem.count("deleted = ?1 and goods.id = ?2" , DeletedStatus.UN_DELETED , goodsId);
    }

    public static List<OrderItem> findAllItemByGoodSerialId(long serialId){
        return find("deleted = ?1 and goods.serialId = ?2 order by id",DeletedStatus.UN_DELETED, serialId).fetch();
    }

    /**
     * 计算某一订单的订单明细数量
     * @param orderId
     * @return
     */
    public static Integer countByOrder(long orderId){
        return ConvertUtil.toInteger(OrderItem.count("deleted = 0 and order.id = ?1 " , orderId));
    }

    public static List<Map<String,Object>> getListByMerchant(Merchant merchant, DistributeStatus distribute_status){
        StringBuilder sb = new StringBuilder(" select oi.id id, o.order_no orderNumber,p.name pname,oi.buy_number buyNumber, oi.amount amount,oi.sale_price salePrice, u.nick_name nickName,ad.address address, ad.phone phone,");
        sb.append(" p.main_image mainImage, p.unit unit ,  p.spec spec,d.id did,d.distribute_status status,d.distribute_type type  from order_items oi  ");
        sb.append(" left join orders o on o.id = oi.order_id  ");
        sb.append("  LEFT JOIN address ad on  o.address_id = ad.id ");
        sb.append("  left join power_web_users u on u.id =  ad.web_user_id ");
        sb.append(" left join goods g on oi.goods_id = g.id   ");
        sb.append(" left join products p ON g.serial_id = p.id   ");
        sb.append("  LEFT JOIN delivery_item d ON d.order_item_id = oi.id  ");
        sb.append(" where  oi.deleted = 0 and 1=1  ").append("and d.merchant_id = ").append(merchant.id.toString());
        if(distribute_status.equals(DistributeStatus.SEND_DISTRIBUTE)){
            sb.append("  and oi.cancel_status is null");
            sb.append("  and (d.distribute_status ='").append(DistributeStatus.USER_GET).append("'");
            sb.append("  or d.distribute_status ='").append(DistributeStatus.SEND_DISTRIBUTE).append("')");
        }else{
            sb.append("  and oi.cancel_status is null");
            sb.append("  and d.distribute_status ='").append(distribute_status.toString()).append("'");
        }
        sb.append(" order by oi.created_at desc");
        Query query = OrderItem.em().createNativeQuery(sb.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resulList = query.getResultList();
        return  resulList;

    }

    public static List<OrderItem> findByOrderId(Order order) {
        return OrderItem.find("order.id = ?1 and deleted = ?2", order.id, DeletedStatus.UN_DELETED).fetch();

    }

    public static List<Map<String,Object>> getListByWebUser(WebUser webUser, DistributeStatus distribute_status){
        StringBuilder sb = new StringBuilder(" select oi.id id, o.order_no orderNumber,p.name pname,oi.buy_number buyNumber, oi.amount amount,oi.sale_price salePrice, ");
        sb.append(" p.main_image mainImage, p.unit unit ,  p.spec spec,d.id did,d.distribute_status status,d.distribute_type type,a.address address ,a.user_name userName,a.phone phone,a.confirm_address confirmAddress , ");
        sb.append(" d.delivery_price deliveryPrice  from order_items oi  ");
        sb.append(" left join orders o on o.id = oi.order_id  ");
        sb.append(" left join goods g on oi.goods_id = g.id   ");
        sb.append(" left join products p ON g.serial_id = p.id   ");
        sb.append("  left JOIN delivery_item d ON d.order_item_id = oi.id  ");
        sb.append(" left join address a on d.address_id= a.id ");
        sb.append(" where  oi.deleted = 0 and 1=1  ");
        sb.append("  and d.distribute_status ='").append(distribute_status.toString()).append("'");
        if(distribute_status != DistributeStatus.DISTRIBUTE) {
            sb.append(" and d.distribute_web_user_id = ").append(webUser.id);
        }
        Query query = OrderItem.em().createNativeQuery(sb.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resulList = query.getResultList();
        return  resulList;

    }

    public static List<Map<String,Object>> getListByWebUserAndTrial(WebUser webUser, DistributeStatus distribute_status){
        StringBuilder sb = new StringBuilder(" select pm.name pmName,pm.id pmId,p.id pId,oi.trial_status trialStatus, r.trial trial,oi.id id, o.order_no orderNumber,p.name pname,oi.buy_number buyNumber, oi.amount amount,oi.sale_price salePrice, ");
        sb.append(" p.main_image mainImage, p.unit unit ,  p.spec spec,d.id did,d.distribute_status status,d.distribute_type type, oi.cancel_status cancelStatus, ");
        sb.append(" d.delivery_price deliveryPrice  from order_items oi  ");
        sb.append(" left join orders o on o.id = oi.order_id  ");
        sb.append(" left join goods g on oi.goods_id = g.id   ");
        sb.append(" left join products p ON g.serial_id = p.id   ");
        sb.append("  left JOIN delivery_item d ON d.order_item_id = oi.id  ");
        sb.append(" LEFT JOIN report r ON r.order_item_id = oi.id ");
        sb.append(" left join power_merchants pm on p.merchant_id = pm.id");
        sb.append(" where  oi.deleted = 0 and 1=1  ");
        sb.append(" and o.web_user_id  = ").append(webUser.id);
        if(distribute_status.equals(DistributeStatus.SEND_DISTRIBUTE ) ){
            sb.append("  and oi.cancel_status is null");
            sb.append("  and (d.distribute_status ='").append(DistributeStatus.SEND_DISTRIBUTE).append("'");
            sb.append("  or d.distribute_status ='").append(DistributeStatus.USER_GET).append("')");
            sb.append("  order  by oi.created_at desc ");
           // sb.append("  order  by d.distribute_status  asc ");
        }else{
            sb.append("  and oi.cancel_status is null");
            sb.append("  and d.distribute_status ='").append(distribute_status.toString()).append("'");
            sb.append("  order  by oi.created_at desc ");
        }
        Logger.info("----------------------sql : %s", sb.toString());
        Query query = OrderItem.em().createNativeQuery(sb.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resulList = query.getResultList();
        return  resulList;

    }

    public static List<Map<String,Object>> getListByOrderId(Order order){
        StringBuilder sb = new StringBuilder(" select oi.id id, o.order_no orderNumber,p.name pname,oi.buy_number buyNumber, oi.amount amount,oi.sale_price salePrice, ");
        sb.append(" p.main_image mainImage, p.unit unit ,  p.spec spec, pm.name pmname ,d.id did,d.distribute_status status,d.distribute_type type,a.address address ,a.user_name userName,a.phone phone,a.confirm_address confirmAddress , ");
        sb.append(" d.delivery_price deliveryPrice  from order_items oi  ");
        sb.append(" left join orders o on o.id = oi.order_id  ");
        sb.append(" left join goods g on oi.goods_id = g.id   ");
        sb.append(" left join products p ON g.serial_id = p.id   ");
        sb.append(" left join power_merchants pm ON p.merchant_id = pm.id   ");
        sb.append("  left JOIN delivery_item d ON d.order_item_id = oi.id  ");
        sb.append(" left join address a on d.address_id= a.id ");
        sb.append(" where  oi.deleted = 0 and 1=1  ");
        sb.append(" and o.id = ").append(order.id);

        Query query = OrderItem.em().createNativeQuery(sb.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resulList = query.getResultList();
        return  resulList;

    }

    public static List<Map<String,Object>> getListForWeiXinMsgByOrderId(Order order){
        StringBuilder sb = new StringBuilder(" select  m.web_user_id from orders o left join order_items oi on o.id = oi.order_id ");
        sb.append(" left join goods g on oi.goods_id = g.id ");
        sb.append(" left join products p on g.serial_Id= p.id   ");
        sb.append(" left join power_merchants m on m.id = p.merchant_id ");
//        sb.append(" where  oi.deleted = 0 and m.verify_state = 'pass'  and 1=1  ");
        sb.append(" where  oi.deleted = 0 and m.verify_state = 'pass'   ");
        sb.append(" and o.id = ").append(order.id);
        sb.append(" GROUP BY m.login_name ");
        Query query = OrderItem.em().createNativeQuery(sb.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resulList = query.getResultList();
        return  resulList;

    }


    public static OrderItem findByIdAndCancelStatus(Long id) {
        return OrderItem.find("id = ?1 and deleted = ?2 and cancelStatus = ?3 ", id, DeletedStatus.UN_DELETED,CancelStatus.CANCEL).first();

    }
    public static OrderItem findByIdDel(Long id) {
        return OrderItem.find("id = ?1 and deleted = ?2 ", id, DeletedStatus.UN_DELETED).first();

    }

    /**
     *  商品销售统计
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    public static List<OrderItem> getSaleStatistics(String name,Integer pageNum,Integer pageSize,String proParentType,String proType){
        StringBuilder sb = new StringBuilder(" select  pt1.`name` pt1Name , pt2.`name` pt2Name ,p.`name` pName, p.unit unit , p.spec spec, IFNULL(SUM(oi.buy_Number),0) sumBuyNumber,FORMAT(IFNULL(SUM(oi.amount),0),2) sumAmount ");
        sb.append(" from order_items oi left join goods g on oi.goods_id = g.id left join products p on g.serial_id =  p.id   ");
        sb.append(" left join product_type pt1 on p.parent_type_id = pt1.id left join product_type pt2 on p.product_type_id = pt2.id where 1=1");
        if( name != null && !name.equals("") ){
            sb.append(" and p.name like '%").append(name).append("%'");
        }
        if( proParentType != null && !proParentType.equals("") ){
            sb.append(" and  pt1.name like '%").append(proParentType).append("%'");
        }
        if( proType != null && !proType.equals("") ){
            sb.append(" and pt2.name like '%").append(proType).append("%'");
        }
        sb.append(" GROUP BY p.name");
        if(pageNum != null){
            sb.append(" LIMIT ").append(pageNum).append(",").append(pageSize);
        }
        Query query = OrderItem.em().createNativeQuery(sb.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<OrderItem> resulList = query.getResultList();
        return  resulList;
    }

    public static  Long getSaleStatisticsByDay(Date beginDate , Date endDate){
        return  OrderItem.count(" createdAt between ?1 and ?2",beginDate,endDate);

    }

    /**
     * 昨日投诉订单数
     * @param beginDate
     * @param endDate
     * @return
     */
    public static List<OrderItem> findYesterdayByTrialStatus(Date beginDate, Date endDate) {
        return OrderItem.find(" deleted = ?1 and   createdAt between ?2 and ?3" , DeletedStatus.UN_DELETED ,beginDate,endDate ).fetch();
    }


    /**
     * 成交量
     */
    public static List<OrderItem> findSumBuyNumberByDay(String beginDate, String endDate){
        String sqlSelect  = " select IFNULL(SUM(o.buy_Number), 0) sumBuyNumber from order_items o  where o.deleted = 0  and o.created_at  between '" + beginDate +"' and '"+endDate +"'";
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<OrderItem> resulList = query.getResultList();
        return  resulList;
    }


    public static List<Map<String,Object>> trialStatusOverListr(String beginDate, String endDay){
        String sqlSelect  = "SELECT  oi.id id,d.id did FROM  order_items oi LEFT JOIN orders o ON o.id = oi.order_id ";
        sqlSelect +=" LEFT JOIN goods g ON oi.goods_id = g.id ";
        sqlSelect +=" LEFT JOIN delivery_item d ON d.order_item_id = oi.id ";
        sqlSelect +=" LEFT JOIN report r ON r.order_item_id = oi.id";
        sqlSelect +=" WHERE oi.deleted = 0 AND 1 = 1 ";
        sqlSelect +=" AND  oi.cancel_status IS NULL";
        sqlSelect +=" AND  d.distribute_status = 'USER_GET' ";
        sqlSelect +=" AND  oi.trial_status IS NULL ";
        sqlSelect +=" AND  oi.created_at  between '"+beginDate+"' and '"+endDay+"'";
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resulList = query.getResultList();
        return  resulList;
    }

    /**
     * 商户成交额
     */
    public static List<OrderItem> findSumAmountByDayAndMer(String beginDate, String endDate , long merId){
        String sqlSelect  = " select FORMAT(IFNULL(sum(a.amount),0),2) sumAmount  FROM order_items a LEFT JOIN orders b ON a.order_id = b.id LEFT JOIN goods c ON a.goods_id = c.id  LEFT JOIN power_merchants pm ON pm.id = c.merchant_id  where a.deleted = 0  and a.created_at  between '" + beginDate +"' and '"+endDate +"'";
        sqlSelect += " and pm.id = "+merId;
        Logger.info("sqlSelect================== : %s", sqlSelect);
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<OrderItem> resulList = query.getResultList();
        return  resulList;
    }

    /**
     * 商户成交量
     */
    public static List<OrderItem> findSumAmountByBuyNumberAndMer(String beginDate, String endDate , long merId){
        String sqlSelect  = " select IFNULL(sum(a.buy_Number),0) buyNumber  FROM order_items a LEFT JOIN orders b ON a.order_id = b.id LEFT JOIN goods c ON a.goods_id = c.id  LEFT JOIN power_merchants pm ON pm.id = c.merchant_id  where a.deleted = 0  and a.created_at  between '" + beginDate +"' and '"+endDate +"'";
        sqlSelect += " and pm.id = "+merId;
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<OrderItem> resulList = query.getResultList();
        return  resulList;
    }

    public static List<OrderItem> findByUserId(long userId) {
        return OrderItem.find("order.webUser.id = ?1 and deleted = ?2", userId, DeletedStatus.UN_DELETED).fetch();

    }


    /**
     * 分页查询.
     */
    public static JPAExtPaginator<OrderItem> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED ")
                .append(" /~ and t.order.webUser.id = {userId} ~/")
                .append(" /~ and t.goods.name like {goodsName} ~/");
        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator<OrderItem> orderPage = new JPAExtPaginator<OrderItem>("OrderItem t", "t", OrderItem.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }



    public static List<Map<String,Object>> findBuySumByUserId(long userId){
        String sqlSelect  = "  select FORMAT(IFNULL(sum(o.amount),0),2) sumAmount from order_items o ";
        sqlSelect += "left join orders os on o.order_id = os.id  where o.deleted = 0 and  os.deleted = 0   ";
        sqlSelect += "  and os.web_user_id = "+userId;
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resulList = query.getResultList();
        return  resulList;
    }

    public static List<Map<String,Object>> findGidPidByMerId(String beginDate, String endDay,long merId){
        String sqlSelect  = " select g.id gid,p.id pid,p.name name from order_items o LEFT JOIN goods g on o.goods_id = g.id ";
        sqlSelect +=" left join products p on g.serial_id = p.id  ";
        sqlSelect +=" where 1=1 ";
        sqlSelect +=" AND p.merchant_id ="+merId;
        sqlSelect +=" AND  o.created_at  between '"+beginDate+"' and '"+endDay+"'";
        sqlSelect +=" GROUP BY g.id ,p.id";
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resulList = query.getResultList();
        return  resulList;
    }

    public static List<Map<String,Object>> findGoodsBuySumByGoodId(String beginDate, String endDay,long productId){
        String sqlSelect  = " select IFNULL(sum(o.buy_number),0) buyNumber from order_items o LEFT JOIN goods g on o.goods_id = g.id  left join products p on g.serial_id = p.id  ";
        sqlSelect +=" where 1=1 ";
        sqlSelect +=" AND p.id = "+productId;
        sqlSelect +=" AND  o.created_at  between '"+beginDate+"' and '"+endDay+"'";
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resulList = query.getResultList();
        return  resulList;
    }

    public static OrderItem findByOrderId(long orderId) {
        return OrderItem.find("order.id = ?1 and deleted = ?2", orderId, DeletedStatus.UN_DELETED).first();

    }




}
